<script setup>
import {ref, onMounted, watch, computed} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {productPageList, addToCart} from '@/api/user'
import {useUserInfoStore} from '@/stores/userInfo'

const route = useRoute()
const router = useRouter()
const product = ref({})
const loading = ref(false)

const loadProduct = async (id) => {
  loading.value = true
  try {
    const res = await productPageList({pageNo: 1, pageSize: 9999})
    const found = res.data.records.find(p => p.id == id)
    if (found) {
      product.value = found
    } else {
      ElMessage.error("未找到该商品")
      router.push('/shopping')
    }
  } catch (err) {
    ElMessage.error("加载商品失败")
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadProduct(route.params.id)
})

watch(() => route.params.id, (newId) => {
  loadProduct(newId)
})

const goBack = () => {
  router.push('/shopping')
}

const userInfoStore = useUserInfoStore()

const userDiscountRate = computed(() => {
  return userInfoStore.userInfo?.discountRate ?? 1
})

const pointsMultiplier = computed(() => {
  return userInfoStore.userInfo?.pointsMultiplier ?? 0
})

// 价格计算函数（与商品列表页保持一致）
const getFinalPrice = (product) => {
  const basePrice = product?.price || 0
  const productDiscountedPrice = product?.discountRate < 1 ? basePrice * product.discountRate : basePrice
  const memberDiscountedPrice = productDiscountedPrice * userDiscountRate.value
  return memberDiscountedPrice.toFixed(2)
}

// 积分返还计算
const getPointsReturn = (product) => {
  const finalPrice = parseFloat(getFinalPrice(product))
  return (finalPrice * 0.1 * pointsMultiplier.value).toFixed(1)
}

// 购物车对话框相关逻辑
const addToCartDialog = ref(false)
const currentProduct = ref(null)
const quantity = ref(1)

// 显示购物车对话框
const showAddToCartDialog = (product) => {
  currentProduct.value = product
  quantity.value = 1
  addToCartDialog.value = true
}

// 处理加入购物车操作
const handleAddToCart = async () => {
  if (!currentProduct.value) return

  try {
    const res = await addToCart(currentProduct.value.id, quantity.value)
    if (res.status === true) {
      ElMessage.success('添加购物车成功')
      addToCartDialog.value = false
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  } catch (error) {
    ElMessage.error('请求出错：' + (error.response?.data?.message || error.message))
  }
}

onMounted(() => {
  userInfoStore.fetchUserInfo()
})

</script>

<template>
  <div class="product-detail">
    <el-card v-loading="loading">
      <div class="detail-header">
        <div v-if="product.inventory <= 0" class="sold-out-badge">已售罄</div>
        <img :src="product.mainImage" class="product-image"/>
        <div class="product-info">
          <h2>{{ product.name }}</h2>

          <div v-if="product.inventory > 0" class="inventory-info">
            库存: {{ product.inventory }}件
          </div>
          <div v-else class="inventory-info out-of-stock-text">
            已售罄
          </div>
          <!-- 价格部分 -->
          <div class="price-section">
            <div v-if="product.discountRate < 1">
              原价：
              <span class="original-price">{{ product.price }} 元</span><br/>
              折扣价：
              <span class="discounted-price">{{ (product.price * product.discountRate).toFixed(2) }} 元</span>
            </div>
            <div v-else>
              售价：
              <span class="normal-price">{{ product.price }} 元</span>
            </div>
            <div v-if="userDiscountRate < 1">
              <div class="member-price">
                会员专享价：
                <strong>{{ getFinalPrice(product) }} 元</strong>
              </div>
              <div class="member-tag">💎 {{ Math.floor(userDiscountRate * 100) }} 折会员</div>
            </div>
            <div v-if="!product.pointsMall && pointsMultiplier > 0" class="points-return">
              购买可返还：{{ getPointsReturn(product) }} 积分
            </div>
            <div v-if="product.pointsMall">
              积分价：<span class="points-price">{{ product.pointsPrice }} 积分</span>
            </div>
          </div>

          <div class="info-row">
            <p>产地：{{ product.origin || '未知' }}</p>
            <p>品牌：{{ product.brand || '暂无信息' }}</p>
            <p>颜色：{{ product.productColor || '无' }}</p>
            <p>尺寸：{{ product.productSize || '无' }}</p>
            <p v-if="product.groupBuy" class="groupbuy-tip">团购热卖中，点击抢购吧！</p>
          </div>
          <div class="info-row flex-gap">
            <el-button
                class="add-to-cart"
                @click="showAddToCartDialog(product)"
                :disabled="product.inventory <= 0"
            >
              {{ product.inventory <= 0 ? '已售罄' : '加入购物车' }}
            </el-button>
            <span style="display: inline-block; width: 20px;"></span>
            <el-button type="primary" @click="goBack">返回列表浏览</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 购物车确认对话框 -->
    <el-dialog
        v-model="addToCartDialog"
        title="添加到购物车"
        width="500px"
    >
      <div v-if="currentProduct" class="cart-dialog-content">
        <div v-if="currentProduct.inventory <= 0" class="stock-warning">
          <el-alert
              title="该商品已售罄，加入购物车后可关注补货通知"
              type="warning"
              show-icon
          />
        </div>
        <div class="product-info">
          <img :src="currentProduct.mainImage" class="product-image" />
          <div class="product-details">
            <h4>{{ currentProduct.name }}</h4>
            <div class="inventory-info">
              库存: {{ currentProduct.inventory }}件
            </div>
            <div v-if="currentProduct.discountRate < 1">
              <span class="original-price">{{ currentProduct.price }} 元</span>
              <span class="discounted-price">{{ (currentProduct.price * currentProduct.discountRate).toFixed(2) }} 元</span>
            </div>
            <div v-else>
              <span class="normal-price">{{ currentProduct.price }} 元</span>
            </div>

            <!-- 会员折扣展示（仅当用户折扣率 < 1） -->
            <div v-if="userDiscountRate < 1">
              <span class="member-price">会员专享价：<strong>{{ getFinalPrice(currentProduct) }} 元</strong></span>
              <div class="member-tag">💎 {{ Math.floor(userDiscountRate * 100) }}折会员</div>
            </div>

            <!-- 积分返还展示（仅非积分商城页） -->
            <div v-if="activeTab !== 'pointsMall' && pointsMultiplier > 0">
              <span class="points-return">返还积分：{{ getPointsReturn(currentProduct) }} 积分</span>
            </div>
          </div>
        </div>

        <el-form label-width="80px">
          <el-form-item label="购买数量">
            <el-input-number
                v-model="quantity"
                :min="1"
                :max="999"
                controls-position="right"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="addToCartDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAddToCart">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 保持原有样式不变 */
.product-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  align-items: flex-start;
}

.product-image {
  width: 100%;
  max-width: 320px;
  height: auto;
  height: 320px;
  object-fit: contain;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.product-info {
  flex: 1;
  min-width: 200px;
}

.original-price {
  text-decoration: line-through;
  color: gray;
}

.discounted-price {
  color: #f56c6c;
  font-weight: bold;
}

.price-section {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
}

.member-price {
  color: #d81e06;
  font-weight: bold;
  margin-top: 4px;
}

.member-tag {
  background-color: #ffe4e1;
  color: #c00;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  margin-top: 4px;
}

.points-return {
  font-size: 13px;
  color: #999;
  margin-top: 6px;
}

.info-row {
  flex-direction: column;
  gap: 10px;
}

.flex-gap {
  gap: 20px;
}

.info-row.flex-gap {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 12px 24px;
  margin-top: 20px;
}

.info-row.flex-gap button {
  max-width: 160px;
  width: auto;
  white-space: nowrap;
  text-align: center;
}

/* 对话框样式 */
.cart-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cart-dialog-content .product-info {
  display: flex;
  gap: 15px;
  align-items: center;
}

.cart-dialog-content .product-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
  border: 1px solid #eee;
  border-radius: 4px;
}

.cart-dialog-content .product-details {
  flex: 1;
}

.cart-dialog-content .product-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.cart-dialog-content .price {
  color: #e53935;
  font-weight: bold;
  font-size: 18px;
}

/* 新增样式 */
.sold-out-badge {
  position: absolute;
  top: 20px;
  left: 20px;
  background-color: #f56c6c;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 2;
}

.out-of-stock-image {
  opacity: 0.7;
  filter: grayscale(30%);
}

.inventory-info {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.out-of-stock-text {
  color: #f56c6c;
  font-weight: bold;
}

.stock-warning {
  margin-bottom: 15px;
}

.add-to-cart:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
